//
//  HDCFBuyFundVc.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/11/2.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFBuyFundVc.h"
#import "SVProgressHUD.h"
#import "InputPassWordView.h"
#import "HDCFRiskTestVc.h"
#import "HDCFMyBankCardVc.h"

@interface HDCFBuyFundVc ()<InputPassWordViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *bankIcon;
@property (weak, nonatomic) IBOutlet UILabel *bankInfo;
@property (weak, nonatomic) IBOutlet UILabel *fundName;
@property (weak, nonatomic) IBOutlet UILabel *fundCode;
@property (weak, nonatomic) IBOutlet UITextField *moneyTf;
@property (weak, nonatomic) IBOutlet UILabel *riskLevel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewToTopConst;

//参考费率
@property (weak, nonatomic) IBOutlet UILabel *consultRate;
//参考费用
@property (weak, nonatomic) IBOutlet UILabel *consultCost;
@property (weak, nonatomic) IBOutlet UILabel *downBuyMoney;
@property (nonatomic, strong) NSArray *bankArray;
@property (nonatomic, strong) NSDictionary *bankDetail;
@property (weak, nonatomic) IBOutlet UILabel *limitMoney;
@property (nonatomic, weak) UIView *hitView;
@property (nonatomic, assign) double maxMoney;
@property (nonatomic, assign) double minMoney;
@property (nonatomic, copy) NSString *tradePassword;
@property (nonatomic, copy) NSString *investorPayId;
@property (weak, nonatomic) IBOutlet UIButton *imagePage;
@property (nonatomic, weak) UIView *clearHudView;

@property (nonatomic, assign) BOOL isBankCard;;


@end

@implementation HDCFBuyFundVc

- (void)setIsLicai:(BOOL)isLicai{
    _isLicai = isLicai;
}

- (void)setDictTwo:(NSDictionary *)dictTwo{
    _dictTwo = dictTwo;
}

- (void)setIsCollcet:(BOOL)isCollcet{
    _isCollcet = isCollcet;
    if (isCollcet == YES) {
        self.viewToTopConst.constant = KNavHeight;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [_imagePage setBackgroundColor:ZKcolor(245, 245, 245)];
    NSString *strleft = @"基金销售服务由奕丰金融提供\n-基金有风险 投资需谨慎-";
    NSMutableAttributedString *attrStrT = [[NSMutableAttributedString alloc] initWithString:strleft];
    [attrStrT addAttribute:NSForegroundColorAttributeName
                     value:[UIColor lightGrayColor]
                     range:NSMakeRange(0, strleft.length)];
    [attrStrT addAttribute:NSFontAttributeName
                     value:[UIFont boldSystemFontOfSize:12]
                     range:NSMakeRange(0, strleft.length)];
    [attrStrT addAttribute:NSFontAttributeName
                     value:[UIFont boldSystemFontOfSize:14]
                     range:NSMakeRange(7, 4)];
    [attrStrT addAttribute:NSForegroundColorAttributeName
                     value:ZKcolor(33, 33, 33)
                     range:NSMakeRange(7, 4)];
    [_imagePage setAttributedTitle:attrStrT forState:UIControlStateNormal];
    [_imagePage setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_imagePage.titleLabel setTextAlignment:NSTextAlignmentCenter];
    _imagePage.titleLabel.lineBreakMode = 0;
    [_imagePage addTarget:self action:@selector(presentPage) forControlEvents:UIControlEventTouchUpInside];
    
    if (_isCollcet == YES) {
        self.viewToTopConst.constant = KNavHeight;
    }
    //注册键盘消失的通
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
    
    [self.navigationItem setTitle:@"基金购买"];
    if (_dataDict) {
        [self setUI];
    }else{
        [self initDataT];
    }
    [self initData];
    [self getBankCardInfo];
}

- (void)presentPage{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *view = [[UIView alloc] init];
    self.clearHudView = view;
    view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
    UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHitTwo)];
    r5.numberOfTapsRequired = 1;
    [view addGestureRecognizer:r5];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(30, (screenHeight - (screenWidth - 60) * 900.0 / 500.0) / 2, screenWidth - 60, (screenWidth - 60) * 900.0 / 500.0);
    imageView.image = [UIImage imageNamed:@"661511947049_.pic_hd.jpg"];
    [view addSubview:imageView];
    view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    [window addSubview:view];
}

- (void)viewHitTwo{
    [self.clearHudView removeFromSuperview];
}

- (void)setUI{
//    self.fundCode.text = _dataDict[@"fundCode"];
    self.fundName.text = _dataDict[@"fundName"];
    NSNumber *riskRate = _dataDict[@"riskRate"];
    if (riskRate.integerValue == 1) {
        _riskLevel.text = @"低风险";
    }else if (riskRate.integerValue == 2){
        _riskLevel.text = @"中低风险";
    }else if (riskRate.integerValue == 3){
        _riskLevel.text = @"中风险";
    }else if (riskRate.integerValue == 4){
        _riskLevel.text = @"中高风险";
    }else{
        _riskLevel.text = @"高风险";
    }
    
    NSString *fundStatus = _dataDict[@"fundStatus"];
    if ([fundStatus isEqualToString:@"0"]) {
        NSNumber *minInitialIpoAmount = _dataDict[@"minInitialIpoAmount"];
        self.minMoney = minInitialIpoAmount.doubleValue;
        NSNumber *maxIpoAmount = _dataDict[@"maxIpoAmount"];
        self.maxMoney = maxIpoAmount.doubleValue;
        self.limitMoney.text = [NSString stringWithFormat:@"(%.2f---%.2f)", minInitialIpoAmount.doubleValue, maxIpoAmount.doubleValue];
    }else if ([fundStatus isEqualToString:@"1"]){
        NSNumber *maxBuyAmount = _dataDict[@"maxBuyAmount"];
        NSNumber *minInitialBuyAmount = _dataDict[@"minInitialBuyAmount"];
        self.limitMoney.text = [NSString stringWithFormat:@"(%.2f---%.2f)", minInitialBuyAmount.doubleValue, maxBuyAmount.doubleValue];
        self.minMoney = minInitialBuyAmount.doubleValue;
        self.maxMoney = maxBuyAmount.doubleValue;
    }
}

- (void)initDataT{
    [SVProgressHUD show];
    NSDictionary *param = @{@"fundCode":_dictTwo[@"productCode"]};
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[KparametTwo] = @"/public/product/get-single-fund-basic";
    NSString *str = [self dictionaryToJson:param];
    NSLog(@"%@", str);
    dict[KparametOne] = [self dictionaryToJson:param];
    [HttpRequest sendGetRequestWithURL:nil WithParamets:dict success:^(id result) {
        if ([result[@"code"] isEqualToString:@"0000"]) {
            
            [SVProgressHUD dismiss];
            self.dataDict = result[@"data"];
            [self setUI];
        }else{
            [SVProgressHUD showErrorWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (void)setDataDict:(NSDictionary *)dataDict{
    _dataDict = dataDict;
}

#pragma mark 购买基金
- (void)buyFund{
    [SVProgressHUD show];
    NSMutableDictionary *fundInfo = [NSMutableDictionary dictionary];
    fundInfo[@"fundCode"] = _dataDict[@"fundCode"];
    fundInfo[@"currency"] = @"156";
    fundInfo[@"investmentAmount"] = self.moneyTf.text;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"accountNumber"] = kAcount;
    dict[@"agreementConfirmed"] = @"0";
    
    dict[@"password"] = self.tradePassword;
    if (self.isBankCard==YES) {
        dict[@"payMethod"] = @"0";
    }
    else
    {
        dict[@"payMethod"] = @"1";
    }
    
    dict[@"purchaseFunds"] = [NSArray arrayWithObjects:fundInfo, nil];
    dict[@"riskConfirmed"] = @"1";
    NSString *jsonString = [self dictionaryToJson:dict];
    NSDictionary *dictThree = @{
                                KparametTwo:@"/public/transaction/buy-fund-transaction"
                                };
    [HttpRequest sendPostRequestWithURL:nil WithParamets:dictThree WithJsonString:jsonString success:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([result[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showSuccessWithStatus:@"购买成功"];
            [SVProgressHUD dismissWithDelay:1.0];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.5];
        }
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"服务器错误，购买失败"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return jsonTemp;
}

- (void)initData{
    
    NSDictionary *paramet = @{
                              KparametTwo:@"/public/investor/find-bank"
                              };
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSDictionary *dict = result[@"data"];
        self.bankArray = [NSArray arrayWithArray:dict[@"data"]];
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (void)getBankCardInfo{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KBankCardInfo};
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dataDict = result[@"data"];
            NSDictionary *investorBankDetails = dataDict[@"investorBankDetails"];
            NSArray *bankArrayt = investorBankDetails[@"data"];
            NSDictionary *bankDetail = bankArrayt.firstObject;
            self.bankDetail = bankDetail;
            self.investorPayId= self.bankDetail[@"investorPayId"];
            NSString *imageName = [NSString stringWithFormat:@"icon_%@", bankDetail[@"bankCode"]];
            self.bankIcon.image = [UIImage imageNamed:imageName];
            for (int i = 0; i < self.bankArray.count; i++) {
                NSDictionary *dict = self.bankArray[i];
                if ([bankDetail[@"bankCode"] isEqualToString:dict[@"bankCode"]]) {
                    NSString *banName = dict[@"bankName"];
                    NSString *cardNo = bankDetail[@"bankNumber"];
                    NSString *laterFour = [cardNo substringFromIndex:(cardNo.length - 4)];
                    self.bankInfo.text = [NSString stringWithFormat:@"%@ 尾号 (%@)", banName, laterFour];
                    break;
                }
            }
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"获取银行卡信息失败"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (void)getRateFee{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
    paramets[@"fundCode"] = _dataDict[@"fundCode"];
    paramets[@"investmentAmount"] = self.moneyTf.text;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KGetFee};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dict = result[@"data"];
            if (![dict[@"salesChargesRate"] isKindOfClass:[NSNull class]]) {
                NSNumber *salesChargesRate = dict[@"salesChargesRate"];
                self.consultRate.text = [NSString stringWithFormat:@"%.2f%%", salesChargesRate.doubleValue];
            }
            if (![dict[@"salesCharges"] isKindOfClass:[NSNull class]]) {
                NSNumber *salesCharges = dict[@"salesCharges"];
                self.consultCost.text = [NSString stringWithFormat:@"%.2f元", salesCharges.doubleValue];
            }
            
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"服务器错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (IBAction)jumpBtn:(UIButton *)sender {
    
    HDCFMyBankCardVc*vc=[[HDCFMyBankCardVc alloc]init];
    vc.isNeedBlock=YES;
    vc.isXianshiWallet=YES;
    vc.isHiddenDeleteBtn = YES;
    vc.block = ^(NSString *name, NSString *bank, NSString *bankId,BOOL isBankCard) {
        self.isBankCard=isBankCard;
        if (isBankCard==YES) {
            self.investorPayId=bankId;
            self.bankInfo.text = [NSString stringWithFormat:@"%@ *** %@", name, bank];
        }
        else
        {
            self.bankInfo.text = [NSString stringWithFormat:@"现金钱包 余额：%@",  name];
        }
        
    };
    
    [self.navigationController pushViewController:vc animated:YES];
    
    [SVProgressHUD dismissWithDelay:1.0];
}

- (IBAction)buyBtnClick:(UIButton *)sender {
    NSString *money = self.moneyTf.text;
    
    if (money.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入购买金额"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    CGFloat buyMoney = money.doubleValue;
    if (buyMoney < self.minMoney) {
        [SVProgressHUD showInfoWithStatus:@"低于最小购买金额"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if (buyMoney > self.maxMoney) {
        [SVProgressHUD showInfoWithStatus:@"大于最大购买金额"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    NSNumber *selfRiskRate = kRiskResult;
    if (!selfRiskRate) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先进行风险评测！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HDCFRiskTestVc *riskVc = [[HDCFRiskTestVc alloc] init];
            [self.navigationController pushViewController:riskVc animated:NO];
            
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
        return;
    }

    NSNumber *funfRiskRate = _dataDict[@"riskRate"];
    //如果自己是保守型，那么除了保守型基金其他都不能购买
    if ([selfRiskRate isEqual:@1]) {
        if (funfRiskRate.integerValue > selfRiskRate.integerValue) {
            [SVProgressHUD showInfoWithStatus:@"您的风险等级为保守型，不能购买超过风险等级的产品"];
            [SVProgressHUD dismissWithDelay:1.5];
            return;
        }
        
    }
    
    if (funfRiskRate.integerValue > selfRiskRate.integerValue) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"此基金的购买风险超出您的风险承受能力，确定要购买吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            UIView *view = [[UIView alloc] init];
            self.hitView = view;
            UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
            r5.numberOfTapsRequired = 1;
            [view addGestureRecognizer:r5];
            
            view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
            view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
            InputPassWordView *inputView = [InputPassWordView InputPassWordView];
            inputView.frame = CGRectMake(30, (screenHeight - 182) / 2, screenWidth - 60, 182);
            inputView.layer.cornerRadius = 5.0;
            inputView.layer.shadowColor = ZKcolor(100, 100, 100).CGColor;//shadowColor阴影颜色
            inputView.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
            inputView.layer.shadowOpacity = 0.7;//阴影透明度，默认0
            inputView.layer.shadowRadius = 3;//阴影半径，默认3
            inputView.clipsToBounds = YES;
            inputView.delegate = self;
            
            [view addSubview:inputView];
            [window addSubview:view];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
    }else{
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIView *view = [[UIView alloc] init];
        self.hitView = view;
        UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
        r5.numberOfTapsRequired = 1;
        [view addGestureRecognizer:r5];
        
        view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
        view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
        InputPassWordView *inputView = [InputPassWordView InputPassWordView];
        inputView.frame = CGRectMake(30, (screenHeight - 182) / 2, screenWidth - 60, 182);
        inputView.layer.cornerRadius = 5.0;
        inputView.layer.shadowColor = ZKcolor(100, 100, 100).CGColor;//shadowColor阴影颜色
        inputView.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
        inputView.layer.shadowOpacity = 0.7;//阴影透明度，默认0
        inputView.layer.shadowRadius = 3;//阴影半径，默认3
        inputView.clipsToBounds = YES;
        inputView.delegate = self;
        
        [view addSubview:inputView];
        [window addSubview:view];
    }
}

- (void)cancelClick{
    [self.hitView removeFromSuperview];
}

- (void)confirmClickWithPassWord:(NSString *)password{
    self.tradePassword = password;
    [self.hitView removeFromSuperview];
    if (password.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入交易密码"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    if (_isLicai == YES) {
        [self buyLiCai];
    }else{
       [self buyFund];
    }
}

- (void)buyLiCai{
    [SVProgressHUD show];
    NSMutableDictionary *fundInfo = [NSMutableDictionary dictionary];
    if (_dictTwo) {
        fundInfo[@"productCode"] = _dictTwo[@"productCode"];
    }else{
        fundInfo[@"productCode"] = _dataDict[@"fundCode"];
    }
    
    fundInfo[@"currency"] = @"156";
    fundInfo[@"investmentAmount"] = self.moneyTf.text;
    fundInfo[@"accountNumber"] = kAcount;
    fundInfo[@"agreementConfirmed"] = @"0";
    
    fundInfo[@"investorPayId"] = self.investorPayId;
    fundInfo[@"password"] = self.tradePassword;
    if (self.isBankCard==YES) {
        fundInfo[@"payMethod"] = @"0";
    }
    else
    {
        fundInfo[@"payMethod"] = @"1";
    }
    fundInfo[@"riskConfirmed"] = @"1";
    NSString *jsonString = [self dictionaryToJson:fundInfo];
    NSDictionary *dictThree = @{
                                KparametTwo:@"/public/product/collective/buy-collective-transaction"
                                };
    [HttpRequest sendPostRequestWithURL:nil WithParamets:dictThree WithJsonString:jsonString success:^(id result) {
        if ([result[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showSuccessWithStatus:@"购买成功"];
            [SVProgressHUD dismissWithDelay:1.0];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.5];
        }
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"服务器错误，购买失败"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (void)viewHit{
    [self.hitView removeFromSuperview];
}

-(void)keyboardWillBeHidden:(NSNotification*)aNotification{
    if (!(self.moneyTf.text.length < 1)) {
        [self getRateFee];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

@end
